import tkinter as tk
from tkinter import filedialog
import os

def open_file():
    file_path = filedialog.askopenfilename(
        initialdir=os.path.expanduser("~/Desktop"),
        title="选择一个 .TBW 文件",
        filetypes=(("TBW 文件", "*.TBW"), ("所有文件", "*.*"))
    )

    if file_path:
        print(f"选择的文件路径: {file_path}")
        read_file(file_path)

def try_encodings(file_path):
    encodings = ['utf-8', 'latin1', 'utf-16', 'gbk', 'big5']
    for enc in encodings:
        try:
            with open(file_path, 'r', encoding=enc) as file:
                content = file.read()
                print(f"\n使用编码 {enc} 读取成功:")
                print(content[:200])  # 只显示前200个字符
        except UnicodeDecodeError:
            print(f"编码 {enc} 读取失败")
        except Exception as e:
            print(f"读取文件失败: {e}")


def read_file(file_path):
    try_encodings(file_path)


root = tk.Tk()
root.title("文件选择示例")
root.geometry("300x150")

btn_open = tk.Button(root, text="选择 .TBW 文件", command=open_file)
btn_open.pack(pady=20)

root.mainloop()